import axios from "axios";
import qs from "qs";
import Uts from "./Uts";
import ZenUI from "@root/components/ZenUI/ZenUI";
// import ToastUtils from './ToastUtils';

/**
 * 通用REST API
 * @namespace REST
 */
let REST = {
	getConfig: function(options = {}) {
		let headerValue = {
			...options
		};
		headerValue["content-type"] = !options.contentType
			? "application/json"
			: "application/x-www-form-urlencoded";
		return {
			headers: headerValue
		};
	},
	getCurrentProjectConfig: function() {
		return {
			baseUrl: ""
		};
	},
	hookWhenGetResponse: function(response, isError) {},
	//for json content type:option={content.type:'json'}
	/**
     * post方式获取服务器数据
     * @param  {string} url    完整链接地址
     * @param  {object} data   请求数据
     * @param  {string} noNoti 提示种类
     * @param  {Object} option contentType改为json或者form-urlencoded，不传时默认json，示例：{contentType:1}
     * @return {promise}        返回promise，支持链式调用。then(successfn,errorfn)
     * @example
     let url = `/store/api/new/homepage/categoryAndProductList`
        let params = {}
        REST.post(url, params).then(function(data) {
            console.log(data);
        }, function(error) {
            console.log('请求错误', error);
        });
     */
	post: function(url, data, noNoti, option = {}) {
		if (data) {
			// data.APIVersion = "V2";
		}
		let _self = this;
		data = option.contentType ? qs.stringify(data) : Uts.toStr(data);
		return new Promise(function(resolve, reject) {
			return axios
				.post(url, data, _self.getConfig(option))
				.then(res => {
					// ToastUtils.hide();
					let resObj = res.data;
					resolve(resObj);
					REST.hookWhenGetResponse(resObj);
					if (
						(resObj.code != "0000" &&
							resObj.code != "1" &&
							resObj.code != "200" &&
							resObj.code != "0002") ||
						(resObj.code == "0002" && noNoti == "show0002")
					) {
						if (resObj.code == "1020") {
							UserApi.toLogin();
						} else {
							if (noNoti != "dis") {
								resObj.message && ZenUI.ST(resObj.message);
							}
						}
					}
				})
				.catch(err => {
					REST.hookWhenGetResponse(err, true);
					// ToastUtils.hide();
					reject(err);
				});
		});
	},
	/**
     * get方式获取服务器数据
     * @param  {string} url    完整链接地址
     * @param  {object} data   请求数据,会自动转换为?a=value&b=value
     * @return {promise}        返回promise，支持链式调用。then(successfn,errorfn)
     * @example
        REST.get('http://baidu.com', {
            wd: '测试的查询'
        }).then(function(data) {
            console.log(data);
        
        }, function(error) {
            console.log(error);
        });
     */
	get: function(url, data) {
		let suffix = typeof data === "object" ? "?" + qs.stringify(data) : "";
		return new Promise(function(resolve, reject) {
			return axios
				.get(url + suffix)
				.then(res => {
					// ToastUtils.hide();
					let resObj = res.data;
					resolve(resObj);
				})
				.catch(err => {
					// ToastUtils.hide();
					reject(err);
				});
		});
	},


	uploadFile: function(url, prams, noNoti, option = {}) {

		let _self = this;
		// data = option.contentType ? qs.stringify(data) : Uts.toStr(data);
		let data = new FormData();
		let keyArr = Object.keys(prams)
		keyArr.forEach((key, index) => {
			data.append(key, prams[key]);
		})

		let config = {
			headers: {"Content-Type": "multipart/form-data"}
		};

		return new Promise(function (resolve, reject) {
			return axios
				.post(url, data, config)
				.then(res => {
					// ToastUtils.hide();
					let resObj = res.data;
					resolve(resObj);

					if (resObj.code != "0000" && resObj.code != "1" && resObj.code != '200' && resObj.code != '0002') {
						if (resObj.code == "1020") {
							UserApi.toLogin();
						} else {
							if (noNoti != "dis") {
								resObj.message && ZenUI.ST(resObj.message);
							}
						}
					}
				})
				.catch(err => {
					// ToastUtils.hide();
					reject(err);
				});
		});

	}

};

export default REST;
